﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.Shell
{
    using System;
    using System.Diagnostics;

    /// <summary>
    /// Provides support for combining service providers.
    /// </summary>
    internal class CombinedServiceProvider : IServiceProvider
    {
        private IServiceProvider mFirst;
        private IServiceProvider mSecond;

        /// <summary>
        /// Combines the two service providers into a single service provider.
        /// </summary>
        /// <param name="first">The first service provider to combine, or a null reference.</param>
        /// <param name="second">The second service provider to combine, or a null reference.</param>
        /// <returns>A combined service provider, or a null reference if both provided service providers are null.</returns>
        public static IServiceProvider Combine(IServiceProvider first, IServiceProvider second)
        {
            if (first == null) return second;
            if (second == null) return first;
            return new CombinedServiceProvider(first, second);
        }

        private CombinedServiceProvider(IServiceProvider first, IServiceProvider second)
        {
            Debug.Assert(first != null);
            Debug.Assert(second != null);
            mFirst = first;
            mSecond = second;
        }

        object IServiceProvider.GetService(Type serviceType)
        {
            object result = mFirst.GetService(serviceType);

            if (result != null)
            {
                return result;
            }

            result = mSecond.GetService(serviceType);

            if (result != null)
            {
                return result;
            }

            return null;
        }
    }
}
